﻿/**************************************************************
 * Copyright gt1987. All rights reserved.
 * 
 * Author: guitao(guitao@eastmoney.com) 
 * Create Date: 2020/5/10 15:36:10
 * Description: HostTaskSchedulerUniqueIdGenerator
 *          
 * Revision History:
 *      Date         Author               Description
 *              
***************************************************************/

using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;

namespace gt.TaskScheduler.Core.Impl
{
    public class HostTaskSchedulerUniqueIdGenerator : ITaskSchedulerUniqueIdGenerator
    {
        private static string _localIp = string.Empty;
        private static object _obj = new object();

        /// <summary>
        /// 以本机Ip地址为uniqueName
        /// </summary>
        /// <returns></returns>
        public string GetUniqueName()
        {
            if (string.IsNullOrEmpty(_localIp))
            {
                lock (_obj)
                {
                    if (string.IsNullOrEmpty(_localIp))
                    {
                        try
                        {
                            var ipArray = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
                            if (ipArray != null && ipArray.Length > 0)
                            {
                                var ip4 = ipArray.FirstOrDefault(p => p.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
                                if (ip4 != null)
                                {
                                    _localIp = ip4.ToString();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.GetLogger().Error("get local host falied", ex);
                            throw ex;
                        }
                    }
                }
            }
            return _localIp;
        }
    }
}
